import { Component, OnInit } from '@angular/core';
import {Navigate} from "../../model/Navigate";
import {NavigateService} from "../../service/navigate.service";
import {DialogService} from "primeng/api";
import {NavigateeditComponent} from "../navigateedit/navigateedit.component";

@Component({
  selector: 'app-navigateadmin',
  templateUrl: './navigateadmin.component.html',
  styleUrls: ['./navigateadmin.component.css']
})
export class NavigateadminComponent implements OnInit {
nl:Array<Navigate>;
  constructor(private navigateService: NavigateService, public dialogService: DialogService) {
    this.nl = new Array();  //实例化对象
  }

  ngOnInit() {
    this.loadNavigateList(); //方法的具体调用
  }


  //获取导航数据数据，存储在nl中
  loadNavigateList() {
    this.navigateService.getNavigateList()
      .then((data: any) => {
        this.nl = data;
      })
  }


  //新闻添加操作
  addNavigate() {
    const ref = this.dialogService.open(NavigateeditComponent, {
      header: '添加新闻',
    });
    //当弹出窗口关闭时触发的事件
    ref.onClose.subscribe((navigate:Navigate) => {
      if(navigate){
        console.log("弹出层关闭时回传的值"+navigate.title);
        this.navigateService.saveNavigate(navigate)
          .then((data:any)=>{
            if(data.msg=='ok'){
              this.loadNavigateList();
            }
            else {
              //弹出错误信息
            }
          })
      }
    });
  }

  // 新闻修改操作
  updateNavigate(id:string){
    let navigate:Navigate;
    navigate=new Navigate();
    this.navigateService.getSingleNavigateById(id)
      .then((data:any)=>{
        if(data){
          navigate=data;
          const ref = this.dialogService.open(NavigateeditComponent, {
            data: {
              "navigate":navigate
            },
            header: '修改导航',
          });
          //当弹出窗口关闭时触发的事件
          ref.onClose.subscribe((navigate:Navigate) => {
            if(navigate){
              console.log("弹出层关闭时回传的值"+navigate.title);
              this.navigateService.saveNavigate(navigate)
                .then((data:any)=>{
                  if(data.msg=='ok'){
                    this.loadNavigateList();
                  }
                  else {
                    //弹出错误信息
                  }
                })
            }
          });
        }
      })
  }

  //新闻删除操作
  deleteNavigate(id:string){
    this.navigateService.deleteNavigate(id)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.loadNavigateList();
        }
        else{
          //弹出报错信息
        }
      })
  }



}
